const Koa = require('koa');

const app = new Koa();
const fs = require('fs');
const router = require('koa-router')();
const serverStatic = require('koa-static');
const send = require('koa-send');
const koaBody = require('koa-body');
const session = require('koa-session2');
const cors = require('koa-cors');

app.use(session({
    key: "SESSIONID",   //default "koa:sess"
}));
app.use(cors());
app.use(serverStatic(__dirname+'/view'));

const MongoClient = require('mongodb').MongoClient;
const DB_CONN_STR = 'mongodb://localhost:27017/xyd';
const ObjectId = require('mongodb').ObjectId;
var insertData = function(db,data, callback) {  
    var collection = db.collection('user');
    collection.insert(data, function(err, result) { 
        if(err)
        {
            console.log('Error:'+ err);
            return;
        }     
        callback(result);
    });
}
const signup = function (arr) {
	return new Promise(function(resolve, reject) {
		MongoClient.connect(DB_CONN_STR, function(err, db) {
			console.log("link ok");
			if (err)
				return reject(err);
			insertData(db,arr, function(result) {
				console.log(result);
				db.close();
				resolve(result.result);
			});
		});
	})
}
var selectData = function(db,name,password, callback) {  
	var collection = db.collection('user');
	var whereStr = {"username":name,"userpassword":password};
	collection.find(whereStr,{_id:0}).toArray(function(err, result) {//, { "username": 1, "userpassword": 1 }
		if(err)
		{
		  console.log('Error:'+ err);
		  return;
		}     
		callback(result);
	});
}
const login = function (username, userpassword) {
	return new Promise(function(resolve, reject) {
		MongoClient.connect(DB_CONN_STR, function(err, db) {
			if (err)
				return reject(err);
			selectData(db,username,userpassword ,function(result) {
				console.log(result);
				db.close();
				resolve(result);
			});
		});
	})
}
var updateData = function(db, callback) {  
    var collection = db.collection('user');
    var whereStr = {"name":'菜鸟教程'};
    var updateStr = {$set: { "url" : "https://www.runoob.com" }};
    collection.update(whereStr,updateStr, function(err, result) {
        if(err)
        {
            console.log('Error:'+ err);
            return;
        }     
        callback(result);
    });
}
var delData = function(db, callback) {   
  var collection = db.collection('user');
  var whereStr = {"name":'菜鸟工具'};
  collection.remove(whereStr, function(err, result) {
    if(err)
    {
      console.log('Error:'+ err);
      return;
    }     
    callback(result);
  });
}

var insertTakeoutFood = function(db,data,callback) {
	var collection = db.collection('tasks');
	collection.insert(data, function(err, result) { 
		if(err)
		{
			console.log('Error:'+ err);
			return;
		}     
		callback(result);
	});
} 
const createTakeoutFood = function(data) {
	return new Promise(function(resolve, reject) {
		MongoClient.connect(DB_CONN_STR, function(err, db) {
			console.log("link ok");
			if (err)
				return reject(err);
			insertTakeoutFood(db,data, function(result) {
				console.log(result);
				db.close();
				resolve(result.result);
			});
		});
	})
}
var selectMyOrder = function(db,name, callback) {  
	var collection = db.collection('tasks');
	var whereStr = {'$or':[{'username':name},{'acceptuser':name}]};
	collection.find(whereStr).toArray(function(err, result) {//, { "username": 1, "userpassword": 1 }
		if(err)
		{
			console.log('Error:'+ err);
			return;
		}     
		callback(result);
	});
}
const myOrder = function (username) {
	return new Promise(function(resolve, reject) {
		MongoClient.connect(DB_CONN_STR, function(err, db) {
			if (err)
				return reject(err);
			selectMyOrder(db,username,function(result) {
				console.log(result);
				db.close();
				resolve(result);
			});
		});
	})
}
var selectAllUnfinishOrder = function(db,callback) {  
	var collection = db.collection('tasks');
	var whereStr = {"taskstate":0,'acceptuser':''};
	collection.find(whereStr).toArray(function(err, result) {//, { "username": 1, "userpassword": 1 }
		if(err)
		{
			console.log('Error:'+ err);
			return;
		}     
		callback(result);
	});
}
const allUnfinishOrder = function () {
	return new Promise(function(resolve, reject) {
		MongoClient.connect(DB_CONN_STR, function(err, db) {
			if (err)
				return reject(err);
			selectAllUnfinishOrder(db,function(result) {
				console.log(result);
				db.close();
				resolve(result);
			});
		});
	})
}
var selectMyUnfinishOrder = function(db,name,callback) {  
	var collection = db.collection('tasks');
	var whereStr = { "$and": [
					{"$or": [{"username": name},{"acceptuser":name}]}, 
					// {"$or": [{"acceptuser": name}]}
				]
				,"taskstate":0
			}
	collection.find(whereStr).toArray(function(err, result) {//, { "username": 1, "userpassword": 1 }
		if(err)
		{
			console.log('Error:'+ err);
			return;
		}     
		callback(result);
	});
}
const myUnfinishOrder = function (name) {
	return new Promise(function(resolve, reject) {
		MongoClient.connect(DB_CONN_STR, function(err, db) {
			if (err)
				return reject(err);
			selectMyUnfinishOrder(db,name,function(result) {
				console.log(result);
				db.close();
				resolve(result);
			});
		});
	})
}
var updateAcceptOrder = function(db,id,name,callback) {
	var collection = db.collection('tasks');
	var whereStr = {"_id":ObjectId(id)};
	var updateStr = {$set: { "acceptuser" : name }};
	collection.update(whereStr,updateStr, {safe:true},function(err, result) {
		if(err)
		{
			console.log('Error:'+ err);
			return;
		}     
		callback(result);
	});
}
const acceptOrder = function (id,name) {
	return new Promise(function(resolve, reject) {
		MongoClient.connect(DB_CONN_STR, function(err, db) {
			if (err)
				return reject(err);
			updateAcceptOrder(db,id,name,function(result) {
				console.log(result);
				db.close();
				resolve(result);
			});
		});
	})
}
var updateCompleteOrder = function(db,id,callback) {
	var collection = db.collection('tasks');
	var whereStr = {"_id":ObjectId(id)};
	var updateStr = {$set: { "taskstate" : 1 }};
	collection.update(whereStr,updateStr, {safe:true},function(err, result) {
		if(err)
		{
			console.log('Error:'+ err);
			return;
		}     
		callback(result);
	});
}
const completeOrder = function (id) {
	return new Promise(function(resolve, reject) {
		MongoClient.connect(DB_CONN_STR, function(err, db) {
			if (err)
				return reject(err);
			updateCompleteOrder(db,id,function(result) {
				console.log(result);
				db.close();
				resolve(result);
			});
		});
	})
}
router.post('/login',koaBody(),async (ctx, next) => {
    await next();//koaBody({multipart: true}),
    ctx.response.type = 'json';
    var ok=[{ok:1,n:1}];
    var no=[{ok:0,n:1}];
    var arr=ctx.request.body;
    // arr =await login(arr.username, arr.userpassword);
    // ctx.body=ctx.session.user=arr[0];
    var temp = await login(arr.username, arr.userpassword);
    if(temp=="")
    	ctx.body = no[0];
    else {
    	ctx.session.user=temp[0];
    	ctx.body = ok[0];
    }
});
router.post('/signup',koaBody(),async (ctx, next) => {
    await next();//koaBody({multipart: true}),
    ctx.response.type = 'json';
    var arr=ctx.request.body;
    arr.userintegral=100;
    ctx.body =  await signup(arr);
});
router.post('/createOrder',koaBody(),async (ctx, next) => {
    await next();
    if(ctx.session.user=='')
    	ctx.body='{ok=-1,n=1}';
    else {
		var tasktypestate=new Array();
		tasktypestate[0]='带外卖';
		tasktypestate[1]='带饭菜';
		ctx.response.type = 'json';
		var arr=ctx.request.body;
		arr.username=ctx.session.user.username;
		arr.taskstate=0;
		arr.tasktypedescribe=tasktypestate[arr.tasktype];
		arr.acceptuser='';
		if(arr.taskstartplace==''){
			arr.taskstartplace=ctx.session.user.userbuildnumber+' 门口';
		}
		if(arr.taskendbuildingplace==''){
			arr.taskendbuildingplace=ctx.session.user.userbuildnumber;
		}
		if(arr.taskendroomplace==''){
			arr.taskendroomplace=ctx.session.user.userbedroomnumber;
		}
		if(arr.tasktime==''){
			arr.tasktime=30;
		}
		arr.taskstarttime=new Date().getTime();
		arr.taskendtime=(new Date().getTime())+arr.tasktime*60*100;
		ctx.body =  await createTakeoutFood(arr);
    }
});
router.get('/myOrder',koaBody(),async (ctx, next) => {
    await next();//koaBody({multipart: true}),
    ctx.response.type = 'json';
    ctx.body =  await myOrder(ctx.session.user.username);
});
router.get('/allUnfinishOrder',koaBody(),async (ctx, next) => {
    await next();//koaBody({multipart: true}),
    ctx.response.type = 'json';
    ctx.body =  await allUnfinishOrder();
});
router.get('/myUnfinishOrder',koaBody(),async (ctx, next) => {
    await next();//koaBody({multipart: true}),
    ctx.response.type = 'json';
    ctx.body =  await myUnfinishOrder(ctx.session.user.username);
});
router.post('/acceptOrder',koaBody(),async (ctx, next) => {
    await next();//koaBody({multipart: true}),
    ctx.response.type = 'json';
    var arr=ctx.request.body;
    var _id=arr.id;
    var _name=ctx.session.user.username;
    ctx.body =  await acceptOrder(_id,_name);
});
router.post('/completeOrder',koaBody(),async (ctx, next) => {
    await next();//koaBody({multipart: true}),
    ctx.response.type = 'json';
    var arr=ctx.request.body;
    var _id=arr.id;
    ctx.body =  await completeOrder(_id);
});
router.get('/',async (ctx, next) => {
    await next();
    ctx.response.type = 'text/html';
    ctx.response.body = fs.createReadStream(__dirname+'/view/index.html');
    console.log(new Date().getTime());
    console.log(new Date().getTime()+30*60*100);
});
router.get('/downloads', async (ctx,next) =>{
    var fileName = 'ssd.apk';
    ctx.attachment(fileName);
    await send(ctx, fileName, { root: __dirname + '/view' });
});

app
    .use(router.routes())
    .use(router.allowedMethods());
app.listen(3333,async (ctx,next) => {
    console.log('app started at port 3333...');
});